/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package drivemachine;

import drivemachine.data2.FolderEntry;
import java.io.*;
import java.util.Date;
import java.util.Vector;

/**
 *
 * @author positron
 */
public class Scanner {
	private int fld;
	private final static String SIG = "DrvM2f3";
	private final static String SIGo1 = "DrvM2f2";
	private final static String SIGser = "DrvM2";
	private final static String SIG3 = "DrvM2015";
	private Date scanDate;

	public int getFolderCount() {return fld; }
	public void incFolderCount() { fld++; }

	private FolderEntry root;

	public FolderEntry getRoot() {
		return root;
	}


	void scan(String root) {
		try {
			root = new File(root).getCanonicalPath();
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
		fld = 0;
		this.scanDate = new Date();
		this.root = new FolderEntry( root );
		this.root.traverse(this);
	}

	public void save(String file) throws IOException {
		try (FileOutputStream out = new FileOutputStream(file)) {
			DataOutputStream oos = new DataOutputStream(out);
			oos.writeUTF(SIG3);
			oos.writeLong(scanDate.getTime());
			root.save3(oos);
		}
	}

	public void load(String file) throws IOException {
		//try {
			FileInputStream in = new FileInputStream(file);
			DataInputStream ios = new DataInputStream(in);
			String sig = ios.readUTF();
			switch(sig) {
				case SIG:
					scanDate = new Date(ios.readLong());
					root = FolderEntry.read(ios, null);
					break;
				case SIG3:
					scanDate = new Date(ios.readLong());
					root = FolderEntry.read3(ios,null);
					break;
				case SIGo1:
					root = FolderEntry.read(ios, null);
					break;
				case SIGser:
					try {
						root = (FolderEntry)((new ObjectInputStream(ios)).readObject());
					} catch(ClassNotFoundException e) {
						throw new IOException("old version failed to load", e);
					}
					break;
				default: throw new IOException("Wrong file format");
			}
			//if(!ios.readUTF().equals(SIG))

		/*} catch (IOException e) {
			e.printStackTrace();
		}*/
	}

	void calcSize() { root.getFullSize(); }

}
